/**
 * @author banglong
 * @date 2016/10/25
 */
define(['text!../html/components/cardManager/cardDetailInfoTemp.html!strip', 'avalon', 'cardManagerApi', 'tools',
    'CardBasic', 'Layer'
  ],
  function (htmlTemp, avalon, api, tools, CardBasic, layer) {

    var cardDetailInfo = function () {

      var runtimeParam;
      var getRuntimeParam = function () {
        return {
          layeroObj: -1
        };
      };

      var cardDetailInfoVm;
      var getVmOption = function () {

        return {
          $id: 'cardDetailInfo',

          // img list
          imgList: [],
          // 是否待报废
          isDbStatus: false,

          // 基本信息附加信息表格
          basicInfoTableHeader: ['物品代码', '物品名称', '物品规格', '数量', '单价', '批次号', '输入人', '输入时间'],
          basicInfoTableRow: ['GoodsCode', 'GoodsName', 'GoodsSpec', 'Counts', 'Price', 'BatchSN', 'UpdateUserName', 'UpdateTime'],
          basicInfoTableData: [],

          // 转移信息表格
          drawInfoTableHeader: ['单据号', '转出部门', '转入部门'],
          drawInfoTableRow: ['BillSN', 'SourceDeptAccountName', 'DestDeptAccountName'],
          drawInfoTableData: [],

          // 维修信息表格
          serviceInfoTableHeader: ['维修单号', '供应商', '单据状态', '开始时间', '结束时间'],
          serviceInfoTableRow: ['RecordSN', 'SupplyName', 'BillStatusStr', 'StartTime', 'EndTime'],
          serviceInfoTableData: [],

          // 报废信息表格
          discardInfoTableHeader: ['报废单号'],
          discardInfoTableRow: ['DiscardBillID'],
          discardInfoTableData: [],

          // 预交款信息表格
          prePayInfoTableHeader: ['预交款', '交款日期', '备注'],
          prePayInfoTableRow: ['PrePayAmount', 'PrePayDate', 'Comment'],
          prePayInfoTableData: [],

          // 增值信息表格
          incrementsInfoTableHeader: ['增值人姓名', '增值信息', '增值金额'],
          incrementsInfoTableRow: ['UpdateUserName', 'GoodsSpec', 'Price'],
          incrementsInfoTableData: [],

          CardBasic: new CardBasic(),
          activeIndex: 1,

          additionInfoHeight: (tools.getBrowserHeightAndWidth().height - 270) / 2,
          payInfoHeight: (tools.getBrowserHeightAndWidth().height - 220),
          addedValueHeight: (tools.getBrowserHeightAndWidth().height - 170),

          tableComponentsID: ['xxx_basic', 'xxx_additionInfo_top',
            'xxx_additionInfo_bottom_left', 'xxx_additionInfo_bottom_right', 'xxx_pay_info', 'xxx_added_value_info'
          ],

          switchCard: function (index) {
            cardDetailInfoVm.activeIndex = index;
          },

          closeLayer: function () {
            layer.close(runtimeParam.layeroObj);
          }
        };
      };

      // 查询卡片详情
      var getSysCard = function (runtimeParam, cardDetailInfoVm, isInit) {
        var layerIndex = layer.load();
        api.getSysCard({
          className: 'CardManager',
          method: 'GetSysCard',
          cardID: runtimeParam.card.CardID,
          isWeb: 'true'
        }).then(function (jsonResult) {

          if (jsonResult.issuccess !== 0) {
            return Promise.reject('获取信息失败');
          }

          //CardBasic     基本信息
          //Attachments   附加信息
          //Increments    增值信息
          //DiscardRecords    报废信息
          //RepairRecords     报修信息
          //TransferRecords   转移信息
          //PrePayRecords     预付款信息
          var result = JSON.parse(jsonResult.result);
          layer.close(layerIndex);
          var CardBasic = new runtimeParam.CardBasic();
          if (result.CardBasic) {
            Object.keys(result.CardBasic).forEach(function (key) {
              if (key === 'GoodsStatusStr') {
                switch (result.CardBasic[key]) {
                  case 'zc':
                    CardBasic[key] = '正常';
                    break;
                  case 'db':
                    CardBasic[key] = '待报废';
                    break;
                  case 'bf':
                    CardBasic[key] = '报废';
                    break;
                }
              } else if (typeof result.CardBasic[key] === 'boolean' || result.CardBasic[key]) {
                CardBasic[key] = result.CardBasic[key];
              }
            })
          }

          cardDetailInfoVm.isDbStatus = CardBasic.GoodsStatusStr === '待报废'
          cardDetailInfoVm.CardBasic = CardBasic;

          if (isInit) {
            cardDetailInfoVm.$watch('isDbStatus', function () {
              // 判断是否更新数据中
              if (!cardDetailInfoVm.isSearching) {
                setCardStatus(cardDetailInfoVm.CardBasic)
              }
            })
          }

          cardDetailInfoVm.basicInfoTableData.pushArray(result.Attachments);
          cardDetailInfoVm.drawInfoTableData.pushArray(result.TransferRecords);
          cardDetailInfoVm.serviceInfoTableData.pushArray(result.RepairRecords);
          cardDetailInfoVm.discardInfoTableData.pushArray(result.DiscardRecords);
          cardDetailInfoVm.prePayInfoTableData.pushArray(result.PrePayRecords);
          cardDetailInfoVm.incrementsInfoTableData.pushArray(result.Increments);

          cardDetailInfoVm.isSearching = false;

        })['catch'](function (ex) {
          layer.close(layerIndex);
          tools.handleError(ex);
        });
      };

      // 获取图片信息
      var getImgInfo = function (CardID) {
        api.getImages({
            className: 'ImageManager',
            method: 'getImages',
            imgType: '7',
            goodsType: 1,
            folder: CardID
          })
          .then(function (data) {
            if (data.issuccess === 0) {
              var result = JSON.parse(data.result);
              if (result.length > 0) {
                // 显示图片幻灯片
                cardDetailInfoVm.imgList = result.splice(0, 10);
              }
            }
          });
      };

      // 设置待报废状态
      var setCardStatus = function(CardBasic) {
        if (CardBasic.GoodsStatusStr && CardBasic.GoodsStatusStr !== '报废' && CardBasic.CardID) {
          // 1 待报废 2 正常
          var type = CardBasic.GoodsStatusStr === '正常' ? 1 : 2

          var id = layer.load();
          api.setCardStatus({
            className: 'CardManager',
            method: 'updateGoodsStatus',
            cardID: CardBasic.CardID,
            type: type,
          })
          .then(function (jsonResult) {
            if (jsonResult.issuccess === 0) {
              cardDetailInfoVm.isSearching = true;
              getSysCard(runtimeParam, cardDetailInfoVm);
            }
            layer.close(id)
          })
          .catch(function (ex) {
            layer.close(id)
            tools.alterError(ex)
          })
        }
      }

      this.init = function (param) {
        runtimeParam = getRuntimeParam();
        runtimeParam = Object.assign({}, runtimeParam, param);
        runtimeParam.CardBasic = CardBasic;
        var vmOption = getVmOption();
        runtimeParam.layeroObj = tools.createNewOpenWindow([tools.getBrowserHeightAndWidth().width - 20 + 'px', tools.getBrowserHeightAndWidth().height - 20 + 'px'],
          '卡片详情', htmlTemp, false, {
            vmConfig: vmOption,
            // 销毁方法
            destroy: function () {
              runtimeParam = null;
              cardDetailInfoVm = null;
            }
          });

        // 选中的数据重新加载 进选中的表格中
        cardDetailInfoVm = tools.initAvalonVm(avalon, vmOption, '.card-detail');

        getSysCard(runtimeParam, cardDetailInfoVm, true);
        getImgInfo(runtimeParam.card.CardID);
      };
    };

    return cardDetailInfo;
  });